#include <stdio.h>
#include "register_login.h"
//用来生成随机盐值
const char char_set[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";

char *generate_Salt(){
    char *salt = (char *)malloc(25);
    if(!salt){
        printf("盐值生成失败\n");
        return NULL;
    }

    strcpy(salt,"$6$");//设置前缀
    //随机生成20个字符
    srand(time(NULL)^getpid());//使用时间和进程ID生成种子

    for(int i = 3;i<19;i++){
        int index = rand()%(sizeof(char_set) - 1);
        salt[i] = char_set[index];
    }
    
    //后缀
    salt[19] = '$';
    salt[20] = '\0';
    return salt;
}
//初始化MYSQL连接
MYSQL * init_Mysql_connection(){
    MYSQL *conn = mysql_init(NULL);
    if(conn == NULL){
        fprintf(stderr,"mysql_init()failed\n");
        return NULL;
    }
    //连接到数据库
    if(mysql_real_connect(conn,"localhost","root","123","zhangsan_db",0,NULL,0)==NULL){
        fprintf(stderr,"mysql_real_connect() failed: %s\n", mysql_error(conn));
        mysql_close(conn);
        return NULL;
    }
    return conn;
}

//创建用户表
int create_UserTable(MYSQL *conn){
    const char *sql = "CREATE TABLE IF NOT EXISTS users ("
                      "id INT AUTO_INCREMENT PRIMARY KEY,"
                      "username VARCHAR(50) NOT NULL UNIQUE,"
                      "salt VARCHAR(50) NOT NULL,"
                      "encrypted_password TEXT NOT NULL,"
                      "is_deleted TINYINT DEFAULT 0)";

    if(mysql_query(conn,sql)){
        fprintf(stderr,"CREATE TABLE failed: %s\n",mysql_error(conn));
        return -1;
    }
    return 0;
}

//注册新用户
int register_NewUser(MYSQL *conn,char *username,const char *password){
    //生成盐值
    char *salt =generate_Salt();
    if(!salt){
        fprintf(stderr,"生成盐值失败\n");
        return -1;
    }

    //使用盐值加密密码
    char *encrypted = crypt(password,salt);
    if(!encrypted){
        fprintf(stderr,"密码加密失败\n");
        free(salt);
        return -1;
    }

    // 添加调试信息
    //size_t encrypted_len = strlen(encrypted);
    //printf("加密密码长度: %zu\n", encrypted_len);
    //printf("加密密码内容: %s\n", encrypted);
    
    //准备SQL语句
    char query[512];
    snprintf(query,sizeof(query),"INSERT INTO users(username, salt, encrypted_password) "
             "VALUES('%s', '%s', '%s')",username,salt,encrypted);

    //执行SQL
    if(mysql_query(conn,query)){
        fprintf(stderr,"INSERT failed: %s\n",mysql_error(conn));
        free(salt);
        return -1;
    }
    printf("用户 %s 注册成功！\n",username);
    free(salt);
    return 0;
}

    //用户注册流程
int User_registration_process(MYSQL *conn){
    // 创建用户表（如果不存在）
    if (create_UserTable(conn) != 0) {
        mysql_close(conn);
        return 1;
    }
    char username[250];
    char password[250];
    printf("=== 用户注册 ===\n");

    //获取用户名
    printf("请输入用户名: ");
    if (fgets(username, sizeof(username), stdin) == NULL) {
        fprintf(stderr, "读取用户名失败\n");
        return 1;
    }

    //移除字符串末尾换行符
    username[strcspn(username, "\n")] = '\0';

    // 获取密码
    printf("请输入密码: ");
    if (fgets(password, sizeof(password), stdin) == NULL) {
        fprintf(stderr, "读取密码失败\n");
        return 1;
    }

    //移除字符串末尾换行符
    password[strcspn(password, "\n")] = '\0';
    
    //注册用户
    if(register_NewUser(conn,username,password)==0){
        //printf("注册成功\n");
        return 0;
    }else{
        printf("注册失败，请重试\n");
        return 1;
    }

}

//登录验证
int login_user(MYSQL *conn,const char *username,const char *password){
    //准备SQL查询
    char query[512];
    snprintf(query,sizeof(query),"SELECT salt, encrypted_password FROM users "
             "WHERE username = '%s' AND is_deleted = 0",username);

    //执行查询
    if(mysql_query(conn,query)!=0){
        fprintf(stderr,"SELECT failed: %s\n",mysql_error(conn));
        return 1;
    }

    //获取结果集并检查是否有结果
    MYSQL_RES *result = mysql_store_result(conn);
    if(result == NULL){
        fprintf(stderr,"mysql_stone_result() failed: %s\n",mysql_error(conn));
        return 1;
    }
    int num_rows = mysql_num_rows(result);
    if(num_rows == 0){
        printf("用户不存在或已经删除\n");
        mysql_free_result(result);//释放结果集资源
        return 1;
    }

    MYSQL_ROW row = mysql_fetch_row(result);

    //获取盐值和加密的密码
    const char *salt = row[0];
    const char *stored_password = row[1];
   // printf("== 调试信息 ==\n");
   // printf("数据库中的盐值: %s\n", salt);
   // printf("数据库中的加密密码: %s\n", stored_password);
   // printf("用户输入的密码: %s\n", password);
    //用盐值加密用户输入的密码与数据库保存的密码进行对比
    char *input_encrypted = crypt(password,salt);
    if(!input_encrypted){
        fprintf(stderr,"用户加密失败\n");
        mysql_free_result(result);
        return 1;
    }
   // printf("新生成的加密密码: %s\n", input_encrypted);
    int match = strcmp(input_encrypted,stored_password);
   // printf("比较结果: %s\n", match == 0 ? "匹配" : "不匹配");
    if(match == 0){
        mysql_free_result(result);
        return 0;
    }else{
        mysql_free_result(result);
        return 1;
    }
}

//用户登录流程
int User_login_process(MYSQL *conn){
    char username[250];
    char password[250];

    printf("=== 用户登录 ===\n");
    //获取用户名
    printf("请输入用户名:");
    if(fgets(username,sizeof(username),stdin)==NULL){
        fprintf(stderr,"读取用户名失败\n");
        mysql_close(conn);
        return 1;
    }

    //移动换行符
    username[strcspn(username,"\n")] = '\0';

    //获取密码
    printf("请输入密码:");
    if(fgets(password,sizeof(password),stdin)==NULL){
        fprintf(stderr,"读取密码失败\n");
        return 1;
    }
    // 移除换行符
    password[strcspn(password, "\n")] = '\0';
    //盐值登录
    if(login_user(conn,username,password)==0){
        printf("\033[32m登录成功！\033[0m\n");
        return 0;
    }else{
        printf("\033[31m登录失败！\033[0m\n");
        return 1;
    }
}

void display_main_menu() {
    printf("\n===== 主菜单 =====\n");
    printf("1. 登录\n");
    printf("2. 注册\n");
    printf("3. 退出\n");
    printf("==================\n");
    printf("请选择: ");
}








//int main(int argc, char *argv[]){
//    printf("Hello world\n");
//    return 0;
//}

